package com.justreading.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @author LYJ
 * @Description 群聊系统的Client端
 * @date 2021 年 10 月 07 日 17:14
 */
public class GroupChatClient {

    private static final int PORT = 6667;
    private static final String HOST = "127.0.0.1";
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;


    public GroupChatClient() throws IOException {
            socketChannel = SocketChannel.open(new InetSocketAddress(HOST,PORT));
            socketChannel.configureBlocking(false);
            selector = Selector.open();
            socketChannel.register(selector,SelectionKey.OP_READ);
            username = socketChannel.getLocalAddress().toString().substring(1);
            System.out.println(username + " is ok");
    }

    public void sendInfo(String info){
        info = username + "说:" + info;
        try{
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public void readInfo(){
        try{
            int readChannel = selector.select();
            if(readChannel > 0){
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()){
                    SelectionKey key = iterator.next();
                    if(key.isReadable()){
                       SocketChannel sc = (SocketChannel)key.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        sc.read(buffer);
                        String msg = new String(buffer.array());
                        System.out.println(msg.trim());
                    }
                    iterator.remove();
                }
            }
        }catch(Exception e){
        }
    }

    public static void main(String[] args) throws IOException {
        GroupChatClient chatClient = new GroupChatClient();
        new Thread(() -> {
            while (true){
                chatClient.readInfo();
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
            String s = scanner.nextLine();
            chatClient.sendInfo(s);
        }
    }
}
